<template>
  <div class="app-container">
    <el-card>
      <el-form :model="queryWarnList" :inline="true" label-width="68px">
        <el-form-item label="预警类型">
          <el-select
            v-model="queryWarnList.alarmsMode"
            placeholder="请选择预警类型"
            clearable
            :style="{ width: '100%' }"
            filterable
            @change="handleAlarmTypeChange"
          >
            <el-option
              v-for="item in alarmType"
              :key="item.warningType"
              :label="item.warningTypeName"
              :value="item.warningType"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="getWarnQuery"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <el-table
        :data="paginatedList"
        border
        height="605px"
        :default-sort="{ prop: 'date', order: 'descending' }"
      >
        <el-table-column prop="code" label="商品编码" align="center" />
        <el-table-column prop="name" label="商品名称" align="center" />
        <el-table-column prop="materialspec" label="商品规格" align="center" />
        <el-table-column
          prop="vbatchcode"
          label="批号"
          sortable
          align="center"
        />
        <el-table-column
          prop="vbatchcodenote"
          label="自定义批次"
          align="center"
        />
        <el-table-column prop="vbillcode" label="单据号" align="center" />
        <el-table-column
          prop="cwarehouse_name"
          label="仓库名称"
          align="center"
        />
        <el-table-column prop="sto_unit_id" label="货位号" align="center" />
        <el-table-column prop="sku_num" label="实际数量" align="center" />
        <el-table-column prop="cunitid" label="单位" align="center" />
        <el-table-column prop="pd_date" label="生产日期" align="center">
          <template #default="{ row }">
            {{
              row.pd_date && row.pd_date !== "1900-01-01 00:00:00"
                ? formatDate(row.pd_date)
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column prop="exp_date" label="有效期" align="center">
          <template #default="{ row }">
            <!-- 仅当复验期无效或为空时，才显示有效期 -->
            {{
              (!row.retest_date || row.retest_date === "1900-01-01 00:00:00") &&
              row.exp_date &&
              row.exp_date !== "1900-01-01 00:00:00"
                ? formatDate(row.exp_date)
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column prop="retest_date" label="复验期" align="center">
          <template #default="{ row }">{{
            formatDate(
              row.retest_date === "1900-01-01 00:00:00" ? null : row.retest_date
            )
          }}</template>
        </el-table-column>
        <el-table-column label="物料状态" min-width="260">
          <template #default="{ row }">
            <el-descriptions size="mini">
              <el-descriptions-item
                v-for="item in numItems"
                :key="item.key"
                v-if="row[item.key] > 0"
              >
                <template slot="label">
                  <span class="label-text">{{ item.label }}</span>
                </template>
                {{ row[item.key] }}
              </el-descriptions-item>
            </el-descriptions>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="total, prev, pager, next, sizes, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
      />
    </el-card>
  </div>
</template>

<script>
import { getSkuAlarms, warningType } from "@/api/report/index.js";

export default {
  data() {
    return {
      queryWarnList: {
        alarmsValues: "",
        alarmsMode: null, // 默认不选择任何预警类型
      },
      pageNum: 1,
      pageSize: 10,
      total: 0,
      alarmsList: [],
      alarmType: [],
      numItems: [
        {
          key: "unqualified_num",
          label: "不合格",
        },
        {
          key: "quarantine_num",
          label: "待检",
        },
        {
          key: "qualified_num",
          label: "合格",
        },
        {
          key: "limit_eligibility_num",
          label: "限制合格",
        },
        {
          key: "sku_no_state_num",
          label: "无库存状态",
        },
        {
          key: "research_num",
          label: "研究用",
        },
        {
          key: "qualified_no_use_num",
          label: "合格(不上市)",
        },
        {
          key: "pending_num",
          label: "待处理",
        },
      ],
    };
  },
  created() {
    this.getTypeList(); // 初始化下拉框数据
  },
  computed: {
    // 分页后的数据
    paginatedList() {
      const startIndex = (this.pageNum - 1) * this.pageSize;
      return this.alarmsList.slice(startIndex, startIndex + this.pageSize);
    },
  },
  methods: {
    // 格式化时间
    formatDate(date) {
      if (!date) return ""; // 如果 `date` 为空或 `null`，返回占位符
      return this.$dayjs(date).isValid()
        ? this.$dayjs(date).format("YYYY-MM-DD")
        : "-";
    },
    // 分页大小变化
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.pageNum = 1; // 重置到第一页
    },
    // 当前页变化
    handleCurrentChange(newPage) {
      this.pageNum = newPage;
    },
    // 获取下拉框数据
    async getTypeList() {
      try {
        const res = await warningType();
        this.alarmType = res.data;
        // 默认选择第一个选项
        if (this.alarmType.length > 0) {
          this.queryWarnList.alarmsMode = this.alarmType[0].warningType;
          this.queryWarnList.alarmsValues = this.alarmType[0].warningTime;
          this.getWarn(); // 初始化数据
        }
      } catch (error) {
        console.error("获取预警类型失败：", error);
      }
    },
    // 监听下拉框选择事件
    handleAlarmTypeChange(value) {
      const selectedOption = this.alarmType.find(
        (item) => item.warningType === value
      );
      this.queryWarnList.alarmsValues = selectedOption
        ? selectedOption.warningTime
        : "";
      this.getWarnQuery(); // 查询数据
    },
    // 查询数据
    async getWarn() {
      try {
        const param = {
          alarmsMode: this.queryWarnList.alarmsMode,
          alarmsValues: this.queryWarnList.alarmsValues,
        };
        const res = await getSkuAlarms(param);
        this.alarmsList = res.data;
        this.total = res.data.length;
      } catch (error) {
        console.error("获取预警数据失败：", error);
      }
    },
    // 查询按钮事件
    getWarnQuery() {
      this.pageNum = 1; // 重置到第一页
      this.getWarn();
    },
  },
};
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
}

.el-card {
  margin-bottom: 20px;
}

.el-pagination {
  float: right;
  margin: 20px;
}
</style>
